package jeye.applet.gui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

import jeye.client.buffer.FrameBuffer;
import jeye.client.thread.FrameBufferThread;

public class VideoPanel extends JPanel implements Runnable {

	private static final long serialVersionUID = 5983618486763971490L;
	
	private boolean paintFlag = false;
	
	private Image image;
	
	private FrameBuffer buffer = new FrameBuffer();
	
	public VideoPanel() {
//		new FrameBufferThread(buffer, 42L, this).start();
	}
	
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		g.setColor(Color.BLACK);
		g.fillRect(0, 0, getWidth(), getHeight());

		if(paintFlag) {
			g.drawImage(image, 0, 0, null);
		} else {
			g.setColor(Color.WHITE);
			g.drawString("Buffering...", 5, 15);
		}
	}

	public void run() {
		try {
			while(true) {
				InputStream stream = buffer.getFrame();
				
				if(stream != null) {
					image = ImageIO.read(stream);
					paintFlag = true;
					repaint();
					
					Thread.sleep(1000 / 15);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
